// 105. 从前序与中序遍历序列构造二叉树

#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
    TreeNode* _build(vector<int>& preorder, vector<int>& inorder, 
                    int& prei, int inbegin, int inend)
    {
        if(inbegin > inend)
            return nullptr;
        
        int rooti = inbegin;
        while(rooti <= inend)
        {
            if(preorder[prei] == inorder[rooti]) break;
            rooti++;
        }
        // 前序确定根
        TreeNode* root = new TreeNode(preorder[prei++]);
        // [inbegin, rooti-1] rooti [rooti+1, inend]

        // 中序分割确定左右子树
        root->left = _build(preorder, inorder, prei, inbegin, rooti-1);
        root->right = _build(preorder, inorder, prei, rooti+1, inend);

        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 
    {
        int i = 0;
        TreeNode* ret = _build(preorder, inorder, i, 0, inorder.size() - 1);
        return ret;
    }
};